<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class OrganizationController extends Controller
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('permission:view-organizations')->only(['index', 'show']);
        $this->middleware('permission:create-organizations')->only(['create', 'store']);
        $this->middleware('permission:edit-organizations')->only(['edit', 'update']);
        $this->middleware('permission:delete-organizations')->only(['destroy']);
    }
    
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // 获取所有根组织（没有父组织的组织）
        $rootOrganizations = Organization::with(['parent', 'children', 'users'])
                            ->whereNull('parent_id')
                            ->get();
        
        // 获取所有组织，用于在没有根组织时显示
        $allOrganizations = Organization::with(['parent', 'children', 'users'])->get();
        
        return view('admin.organizations.index', compact('rootOrganizations', 'allOrganizations'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $organizations = Organization::all();
        return view('admin.organizations.create', compact('organizations'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50|unique:organizations,code',
            'description' => 'nullable|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'website' => 'nullable|url|max:255',
            'is_active' => 'boolean',
            'parent_id' => 'nullable|exists:organizations,id',
            'admin_users' => 'nullable|array',
            'admin_users.*' => 'exists:users,id',
            'member_users' => 'nullable|array',
            'member_users.*' => 'exists:users,id',
        ]);
        
        // 处理Logo上传
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('organizations', 'public');
            $validated['logo'] = $logoPath;
        }
        
        $organization = Organization::create($validated);
        
        // 添加管理员
        if ($request->has('admin_users')) {
            foreach ($request->admin_users as $userId) {
                $organization->users()->attach($userId, ['is_admin' => true]);
            }
        }
        
        // 添加普通成员
        if ($request->has('member_users')) {
            foreach ($request->member_users as $userId) {
                // 确保用户不是管理员才添加为普通成员
                if (!$request->has('admin_users') || !in_array($userId, $request->admin_users)) {
                    $organization->users()->attach($userId, ['is_admin' => false]);
                }
            }
        }
        
        return redirect()->route('admin.organizations.index')
                         ->with('success', '组织创建成功！');
    }

    /**
     * Display the specified resource.
     */
    public function show(Organization $organization)
    {
        $organization->load('parent', 'children', 'users.roles');
        $admins = $organization->admins()->with('roles')->get();
        $members = $organization->users()->wherePivot('is_admin', false)->with('roles')->get();
        
        return view('admin.organizations.show', compact('organization', 'admins', 'members'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Organization $organization)
    {
        $organizations = Organization::where('id', '!=', $organization->id)->get();
        $adminIds = $organization->admins()->pluck('users.id')->toArray();
        $memberIds = $organization->users()->wherePivot('is_admin', false)->pluck('users.id')->toArray();
        $users = User::with('roles', 'organizations')->get();
        
        return view('admin.organizations.edit', compact('organization', 'organizations', 'users', 'adminIds', 'memberIds'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Organization $organization)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => ['nullable', 'string', 'max:50', Rule::unique('organizations')->ignore($organization->id)],
            'description' => 'nullable|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'website' => 'nullable|url|max:255',
            'is_active' => 'boolean',
            'parent_id' => 'nullable|exists:organizations,id',
            'admin_users' => 'nullable|array',
            'admin_users.*' => 'exists:users,id',
            'member_users' => 'nullable|array',
            'member_users.*' => 'exists:users,id',
        ]);
        
        // 确保不会选择自己作为父组织
        if ($request->parent_id == $organization->id) {
            return back()->withErrors(['parent_id' => '不能选择自己作为父组织'])->withInput();
        }
        
        // 处理Logo上传
        if ($request->hasFile('logo')) {
            // 删除旧logo
            if ($organization->logo) {
                Storage::disk('public')->delete($organization->logo);
            }
            
            $logoPath = $request->file('logo')->store('organizations', 'public');
            $validated['logo'] = $logoPath;
        }
        
        $organization->update($validated);
        
        // 更新用户关系
        $organization->users()->detach(); // 先移除所有用户关系
        
        // 添加管理员
        if ($request->has('admin_users')) {
            foreach ($request->admin_users as $userId) {
                $organization->users()->attach($userId, ['is_admin' => true]);
            }
        }
        
        // 添加普通成员
        if ($request->has('member_users')) {
            foreach ($request->member_users as $userId) {
                // 确保用户不是管理员才添加为普通成员
                if (!$request->has('admin_users') || !in_array($userId, $request->admin_users)) {
                    $organization->users()->attach($userId, ['is_admin' => false]);
                }
            }
        }
        
        return redirect()->route('admin.organizations.index')
                         ->with('success', '组织更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Organization $organization)
    {
        // 检查是否有子组织
        if ($organization->children()->count() > 0) {
            return back()->with('error', '无法删除存在子组织的组织，请先删除或移动子组织。');
        }
        
        // 删除logo文件
        if ($organization->logo) {
            Storage::disk('public')->delete($organization->logo);
        }
        
        // 删除组织
        $organization->users()->detach(); // 移除所有用户关系
        $organization->delete();
        
        return redirect()->route('admin.organizations.index')
                         ->with('success', '组织删除成功！');
    }
    
    /**
     * 添加用户到组织
     */
    public function addUser(Request $request, Organization $organization)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'is_admin' => 'boolean',
        ]);
        
        // 检查用户是否已经在组织中
        if ($organization->users()->where('user_id', $request->user_id)->exists()) {
            return back()->with('error', '该用户已经是组织成员！');
        }
        
        $organization->users()->attach($request->user_id, [
            'is_admin' => $request->is_admin ?? false,
        ]);
        
        return back()->with('success', '用户已添加到组织！');
    }
    
    /**
     * 从组织中移除用户
     */
    public function removeUser(Request $request, Organization $organization)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);
        
        $organization->users()->detach($request->user_id);
        
        return back()->with('success', '用户已从组织中移除！');
    }
    
    /**
     * 更改用户在组织中的角色
     */
    public function changeUserRole(Request $request, Organization $organization)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'is_admin' => 'required|boolean',
        ]);
        
        $organization->users()->updateExistingPivot($request->user_id, [
            'is_admin' => $request->is_admin,
        ]);
        
        $roleText = $request->is_admin ? '管理员' : '普通成员';
        return back()->with('success', "用户角色已更改为{$roleText}！");
    }
}
